﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Com;
using DAL.MySQL;
using Models;
using PetaPoco;

namespace Core
{
    public class adminCore
    {
        private readonly adminDAL dal= new adminDAL();

        public adminEntity GetAdminByNP(string username, string password)
        {

            password = DESEncrypt.Encrypt(password);
            var model = dal.GetOneByUN(username, password);
            if (model != null)
            {
                model.logintime=DateTime.Now;
                model.ip = Utils.GetAddressIP();
                model.hits++;
                dal.Save(model);
                model.password = null;
            }
            return model;
        }
        public adminEntity GetOne(int id)
        {
            return dal.GetOne(id)==null?new adminEntity():dal.GetOne(id);
        }
        public adminEntity GetSafeOne(int id)
        {
            var model = dal.GetOne(id);
            if (model != null)
            {
                model.password = null;
            }
            else
            {
                model = new adminEntity();
            }

            return model;
        }

        public adminEntity SaveSelf(adminEntity model)
        {
            var lsmodel = dal.GetOne(model.ID);
            if (string.IsNullOrEmpty(model.password))
            {
                model.password = lsmodel.password;
            }
            else
            {
                model.password = DESEncrypt.Encrypt(model.password);
            }
            model.utype = lsmodel.utype;
            return dal.Save(model);

        }
        public adminEntity Save(adminEntity model)
        {
            if (model.ID > 0)
            {
                var lsmodel = dal.GetOne(model.ID);
                if (string.IsNullOrEmpty(model.password))
                {
                    model.password = lsmodel.password;
                }
                else
                {
                    model.password = DESEncrypt.Encrypt(model.password);
                }
            }
            else
            {
                model.password= DESEncrypt.Encrypt(model.password);
            }
            return dal.Save(model);
        }
        public int Update(object obj, int ID)
        {
            return dal.Update(obj, ID);
        }
        public bool Del(int id)
        {
            return dal.Del(id);
        }
        public bool Del(adminEntity model)
        {
            return dal.Del(model);
        }
        public List<adminEntity> GetList(int top, string where, string order, params object[] args)
        {
            return dal.GetPageList(1, top, where, order, args).Items;
        }
        public Page<adminEntity> GetPage(int page, int pagesize, string where, string order, params object[] args)
        {
            return dal.GetPageList(page, pagesize, where, order, args);
        }
    }
}
